package cn.etgps.etgps.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.List;

import cn.etgps.etgps.R;
import cn.etgps.etgps.dataEntity.Model;
import cn.etgps.etgps.dataEntity.TruckBean;
import cn.etgps.etgps.ui.MapMarkerActivity;
import cn.etgps.etgps.ui.TrackReplaySettingActivity;
import cn.etgps.etgps.ui.TruckDetailActivity;
import cn.etgps.etgps.utils.AppUtils;

/**
 * 车辆列表的Adapter
 * Created by Nicky on 2015/11/23.
 */
public class GarageListAdapter extends BaseAdapter {
    /**
     * List data
     */
    private List<Model> mData = null;
    /**
     * Provide item view
     */
    private ViewHolder mHolder = null;
    /**
     * Used to load view from layout file
     */
    private LayoutInflater mInflater = null;
    /**
     * 通过List控件根据tag 获取指定ch
     */
    private ListView mListView = null;
    /**
     * Use to get resource
     */
    private Context mContext = null;
    /**
     * 显示按钮
     */
    private PopupWindow mButtonGroupWindow = null;

    public GarageListAdapter(Context context, ListView listview, List<Model> data) {
        mContext = context;
        mData = data;
        mListView = listview;
        mInflater = LayoutInflater.from(context);
    }

    /**
     * 重新设置数据
     */
    public void resetData(List<Model> data) {
        mData = data;
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mData.get(position).getId();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final TruckBean truckStatusBean = (TruckBean) mData.get(position);
        if (truckStatusBean == null) {
            return null;
        }
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.garage_list_item_view, null);
            mHolder = new ViewHolder();
            mHolder.licensePlate = (TextView) convertView.findViewById(R.id.license_plate);
            mHolder.belonging = (TextView) convertView.findViewById(R.id.belonging);
            mHolder.updateTime = (TextView) convertView.findViewById(R.id.update_time);
            mHolder.status = (TextView) convertView.findViewById(R.id.acc_state);
            mHolder.speed = (TextView) convertView.findViewById(R.id.speed);
            mHolder.direction = (TextView) convertView.findViewById(R.id.direction);
            mHolder.distance = (TextView) convertView.findViewById(R.id.distance);
            mHolder.address = (TextView) convertView.findViewById(R.id.address);
            mHolder.detailViewGroup = convertView.findViewById(R.id.detail_group);
            mHolder.btnGroup = (Button) convertView.findViewById(R.id.btn_group);
            mHolder.stopTime = (TextView) convertView.findViewById(R.id.stopTime);
            mHolder.fuelCost = (TextView) convertView.findViewById(R.id.fuelCost);
            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }

        mHolder.belonging.setBackgroundResource(R.drawable.black_small_rectangle);
        mHolder.belonging.setTextColor(Color.YELLOW);
        //        mHolder.status.setText(mContext.getString(R.string.item_acc_status_title) + truckStatusBean
        // .getStatus());
        String accStatus = truckStatusBean.getStatus();
        if (accStatus.contains(mContext.getString(R.string.label_truck_acc_status_opened))) {
            mHolder.status.setText(mContext.getString(R.string.item_acc_status_title) + mContext.getString(
                    R.string.label_truck_acc_status_opened));
        } else if (accStatus.contains(mContext.getString(R.string.label_truck_acc_status_closed))) {
            mHolder.status.setText(mContext.getString(R.string.item_acc_status_title) + mContext.getString(
                    R.string.label_truck_acc_status_closed));
        } else if (accStatus.contains(mContext.getString(R.string.label_truck_acc_status_flameout))) {
            mHolder.status.setText(mContext.getString(R.string.item_acc_status_title) + mContext.getString(
                    R.string.label_truck_acc_status_flameout));
        } else if (accStatus.contains(mContext.getString(R.string.label_truck_engine_opened))) {
            mHolder.status.setText(mContext.getString(R.string.item_acc_status_title) + mContext.getString(
                    R.string.label_truck_engine_opened));
        } else if (accStatus.contains(mContext.getString(R.string.label_truck_engine_closed))) {
            mHolder.status.setText(mContext.getString(R.string.item_acc_status_title) + mContext.getString(
                    R.string.label_truck_engine_closed));
        } else {
            mHolder.status.setText(mContext.getString(R.string.item_acc_status_title));
        }
        mHolder.speed.setText(
                mContext.getString(R.string.item_acc_speed_title) + truckStatusBean.getSpeed() + mContext.getString(
                        R.string.item_acc_speed_unit));
        mHolder.direction.setText(mContext.getString(R.string.item_btn_direction_info) + AppUtils.getDirectionString(
                truckStatusBean.getDirection()));  //需要换算
        mHolder.stopTime.setText(
                mContext.getString(R.string.stop_time) + AppUtils.getStopTime(truckStatusBean.getStopTime()));
        if (!truckStatusBean.getFuel().equals("")) {
            mHolder.fuelCost.setText(
                    mContext.getString(R.string.fuel_cost) + truckStatusBean.getFuel() + mContext.getString(
                            R.string.percent));
        } else {
            mHolder.fuelCost.setVisibility(View.GONE);
        }
        if (truckStatusBean.getTotalDistance().equals("")) {
            mHolder.distance.setText(mContext.getString(R.string.item_acc_distance_title));
        } else {
            mHolder.distance.setText(mContext.getString(R.string.item_acc_distance_title) + Math.round(
                    Float.parseFloat(truckStatusBean.getTotalDistance())) + mContext.getString(
                    R.string.item_acc_distance_unit));
        }
        String license = truckStatusBean.getLicense();
        if (license.length() > 8) {
            license = license.substring(0, 8) + "...";
        }
        mHolder.licensePlate.setText(license);
        mHolder.belonging.setText(mContext.getString(R.string.truck_belong_self));  //现在全部是自有的
        mHolder.updateTime.setText(AppUtils.reFormatTimeWithoutSeconds(truckStatusBean.getGpsTime()));
        if (truckStatusBean.getLocation() != null && !truckStatusBean.getLocation().equals("")) {
            mHolder.address.setTextColor(mContext.getResources().getColor(R.color.blue_color));
            mHolder.address.setText(Html.fromHtml("<u>" + truckStatusBean.getLocation() + "</u>"));
            mHolder.address.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, MapMarkerActivity.class);
                    intent.putExtra("Model", truckStatusBean);
                    mContext.startActivity(intent);
                }
            });
        } else {
            mHolder.address.setTextColor(mContext.getResources().getColor(R.color.dark_gray_color));
            mHolder.address.setText(mContext.getString(R.string.item_get_no_address));
        }
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCategoryChooseWindow(position);
            }
        };
        mHolder.btnGroup.setTag(position);
        mHolder.btnGroup.setOnClickListener(listener);
        return convertView;
    }

    /**
     * 显示按钮组合
     */
    public void showCategoryChooseWindow(final int position) {
        if (position < 0 || position >= mData.size()) {
            return;
        }
        View mBtnGroupView = mInflater.inflate(R.layout.truck_list_item_btn_group, null);
        mButtonGroupWindow = new PopupWindow(mBtnGroupView, AbsListView.LayoutParams.WRAP_CONTENT,
                AbsListView.LayoutParams.WRAP_CONTENT, true);
        mButtonGroupWindow.setOutsideTouchable(true);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        mButtonGroupWindow.setBackgroundDrawable(dw);
        mBtnGroupView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    hideCategoryChooseWindow();
                }
                return false;
            }
        });
        Button detailBtn = (Button) mBtnGroupView.findViewById(R.id.btn_truck_detail);
        detailBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, TruckDetailActivity.class);
                TruckBean truckStatusBean = (TruckBean) mData.get(position);
                intent.putExtra("vid", truckStatusBean.getVID());
                mContext.startActivity(intent);
                hideCategoryChooseWindow();
            }
        });
        Button playbackBtn = (Button) mBtnGroupView.findViewById(R.id.btn_playback);
        playbackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, TrackReplaySettingActivity.class);
                intent.putExtra("Model", ((TruckBean) mData.get(position)));
                mContext.startActivity(intent);
                hideCategoryChooseWindow();
            }
        });
        hideCategoryChooseWindow();
        View view = mListView.findViewWithTag(position);
        mButtonGroupWindow.showAsDropDown(view, -248, -81);
    }

    /**
     * Hide menu
     */
    public void hideCategoryChooseWindow() {
        if (null != mButtonGroupWindow && mButtonGroupWindow.isShowing()) {
            mButtonGroupWindow.dismiss();
        }
    }

    static class ViewHolder {
        TextView licensePlate;
        TextView belonging;
        TextView updateTime;
        TextView status;
        TextView speed;
        TextView direction;
        TextView distance;
        TextView address;
        View detailViewGroup;
        TextView stopTime;
        TextView fuelCost;
        Button btnGroup;
    }
}
